package com.hxy.travel.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.hxy.travel.pojo.Permission;
import com.hxy.travel.pojo.Role;
import com.hxy.travel.pojo.User;
import com.hxy.travel.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component(value = "userService")
public class SpringSecurityUserService  implements UserDetailsService {
    @Reference
    private UserService userService;


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        User user = userService.findUserByUserName(s);

        if(user == null){
            return null;
        }
        List<GrantedAuthority> authorityList = new ArrayList<>();

        Set<Role> roles = user.getRoles();

        for (Role role : roles) {
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions){
                authorityList.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }

        }
        UserDetails userDetails = new org.springframework.security.core.userdetails.User( user.getUsername(), user.getPassword(),authorityList);
        return userDetails;
    }
}
